package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.beans.HospitalStatusBean;
import com.hxkcloud.patient.dborm.HospitalStatusDao;
import com.hxkcloud.patient.popup.CalendarPopWindow;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.StringUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * Created by william_sun on 2016-07-07.
 * Description:患者状态选择（在院，出院，已退出）
 */
public class PatientStatusSelectActivity extends BaseActivity implements View.OnClickListener {
    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;

//    private LinearLayout ll_in;
//    private LinearLayout ll_out;
//    private LinearLayout ll_quit;
//    private ImageView iv_in;
//    private ImageView iv_out;
//    private ImageView iv_quit;

    private ListView lv_status;
    private statusAdapter adapter;

    private String status = "0";
    private String patientId = "";
    private String clickId = "";

    private Intent iBack;

    private List<HospitalStatusBean> hospitalStatus;

    private LinearLayout selectTimelayout;
    private TextView chuyaunTimeTV;
    private TextView fuzhenTimeTV;

    private CalendarPopWindow calendarView;
    private boolean isChuyuanTime = false;
    private boolean isFuzhenTime = false;

    private TextView tv_notice;

    private Button submitBtn;

    //出院时间和复诊时间
    private String cyId = "";
    private String cyTime = "";
    private String fzId = "";
    private String fzTime = "";

    private boolean isIntentNotice = false;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_MODIFYHOSPITALSTATUS_SUCCESS:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                }
                adapter.notifyDataSetChanged();
                break;
            case MessageCode.NETWORKCODE_MODIFYHOSPITALSTATUS_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(getResources().getString(R.string.datamodifyfail));
                }
                break;
            case MessageCode.NETWORKCODE_HOSPITALTIMEUPDATE_SUCCESS:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(getResources().getString(R.string.save_success));
                    if (isIntentNotice) {
//                        Intent intent = new Intent(mContext, NoticeActivity.class);
                        Intent intent = new Intent(mContext, PatientBetterPlanActivity.class);
                        intent.putExtra("patientId", patientId);
                        intent.putExtra("isFuzhen", true);
                        startActivity(intent);

                        iBack.putExtra("status", clickId);
                        iBack.putExtra("finish", true);
                        setResult(RESULT_OK, iBack);
                        finish();
                    } else {
                        iBack.putExtra("status", clickId);
                        iBack.putExtra("finish", true);
                        setResult(RESULT_OK, iBack);
                        finish();
                    }


                } else {
                    toastMsg(getResources().getString(R.string.datamodifyfail));
                }
                break;
            case MessageCode.NETWORKCODE_HOSPITALTIMEUPDATE_FAILURE:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(getResources().getString(R.string.datamodifyfail));
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patientstatusselect);

        Intent iGet = getIntent();
        status = iGet.getStringExtra("status");
        patientId = iGet.getStringExtra("patientId");
        if (iGet.hasExtra("cyId")) {
            cyId = iGet.getStringExtra("cyId");
        }
        if (iGet.hasExtra("cyTime")) {
            cyTime = iGet.getStringExtra("cyTime");
        }
        if (iGet.hasExtra("fzId")) {
            fzId = iGet.getStringExtra("fzId");
        }
        if (iGet.hasExtra("fzTime")) {
            fzTime = iGet.getStringExtra("fzTime");
        }

        iBack = new Intent(mContext, PatientInfoActivity.class);

        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(getResources().getText(R.string.statusselect));

        selectTimelayout = (LinearLayout) findViewById(R.id.patientstatusselect_layout_timeselect);
        chuyaunTimeTV = (TextView) findViewById(R.id.patientstatusselect_tv_chuyuan);
        fuzhenTimeTV = (TextView) findViewById(R.id.patientstatusselect_tv_fuzhen);
        tv_notice = (TextView) findViewById(R.id.patientstatusselect_tv_notice);
        submitBtn = (Button) findViewById(R.id.patientstatusselect_btn_submit);

        HospitalStatusDao hospitalStatusDao = new HospitalStatusDao(mContext);
        hospitalStatus = hospitalStatusDao.getHospitalStatus(StringUtil.isCurChanke(loginInfo.getDepartmentId(), mContext));
        for (HospitalStatusBean s : hospitalStatus) {
            if (s.getItemId().equals(status)) {
                s.setIsSelect(true);
                if (getResources().getText(R.string.outhospital).equals(s.getName())) {
                    selectTimelayout.setVisibility(View.VISIBLE);
                    tv_notice.setVisibility(View.VISIBLE);
                    submitBtn.setVisibility(View.VISIBLE);
                }
            } else {
                s.setIsSelect(false);
            }
        }

        lv_status = (ListView) findViewById(R.id.lv_statusselect);

        adapter = new statusAdapter();
        lv_status.setAdapter(adapter);
        lv_status.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                clickId = hospitalStatus.get(position).getItemId();

                if (getResources().getText(R.string.outhospital).equals(hospitalStatus.get(position).getName())) {
                    selectTimelayout.setVisibility(View.VISIBLE);
                    tv_notice.setVisibility(View.VISIBLE);
                    submitBtn.setVisibility(View.VISIBLE);
                } else {
                    if (hospitalStatus.get(position).getName().equals("在院")) {
                        StringUtil.zhugeTrack(mContext, "管理-患者信息-在院", "在院点击数");
                    }
                    selectTimelayout.setVisibility(View.GONE);
                    tv_notice.setVisibility(View.GONE);
                    submitBtn.setVisibility(View.GONE);
                }
                for (HospitalStatusBean s : hospitalStatus) {
                    if (s.getItemId().equals(clickId)) {
                        s.setIsSelect(true);
                    } else {
                        s.setIsSelect(false);
                    }
                }
                loading();
                YiJiaHuNetWorkUtils.modifyHospitalStatus(patientId, clickId, handler);

            }
        });

        if (calendarView == null) {
            calendarView = new CalendarPopWindow(this);
        }
        calendarView.setCalendarListener(new CalendarPopWindow.CalendarListener() {
            @Override
            public void setCalendar(String calendar) {
                if (isChuyuanTime) {
                    isChuyuanTime = false;

                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    long dateSelect = 0;
                    try {
                        dateSelect = sdf.parse(calendar).getTime();
                    } catch (ParseException e) {
                    }
                    long nowDate = Calendar.getInstance().getTime().getTime();
                    if (dateSelect > nowDate) {
                        toastMsg(R.string.selectdatecantlaterthannow);
                        return;
                    }

                    chuyaunTimeTV.setText(calendar);
                }
                if (isFuzhenTime) {
                    isFuzhenTime = false;
                    fuzhenTimeTV.setText(calendar);
                }

            }
        });


    }

    @Override
    protected void initListener() {

        chuyaunTimeTV.setOnClickListener(this);
        fuzhenTimeTV.setOnClickListener(this);
        submitBtn.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String curDay = sdf.format(cal.getTime());
        if (!TextUtils.isEmpty(cyTime)) {
            chuyaunTimeTV.setText(cyTime);
        } else {
            chuyaunTimeTV.setText(curDay);
        }

        if (!TextUtils.isEmpty(fzTime)) {
            fuzhenTimeTV.setText(fzTime);
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                iBack.putExtra("status", clickId);
                setResult(RESULT_OK, iBack);
                finish();
                break;
            case R.id.patientstatusselect_tv_chuyuan:
                isChuyuanTime = true;
//                calendarView.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
//                BrightnessUtils.lightOff(this);
                calendarView.showBottom(ll_title);
                break;
            case R.id.patientstatusselect_tv_fuzhen:
                isFuzhenTime = true;
//                calendarView.showAtLocation(ll_title, Gravity.BOTTOM, 0, 0);
//                BrightnessUtils.lightOff(this);
                calendarView.showBottom(ll_title);
                break;
            case R.id.patientstatusselect_btn_submit:
//                Intent intent = new Intent(this, NoticeActivity.class);
//                intent.putExtra("patientId", patientId);
//                startActivity(intent);
                StringUtil.zhugeTrack(mContext, "管理-患者信息-出院-保存按钮", "出院点击数");

                String newtime = fuzhenTimeTV.getText().toString().trim();
                if (TextUtils.isEmpty(fzTime) && newtime.equals("请选择")) {//初始状态
                    isIntentNotice = false;
                } else if (fzTime.equals(newtime)) {
                    isIntentNotice = false;
                } else {
                    isIntentNotice = true;
                }

                loading();
                if (newtime.contains("-")) {
                    fzTime = newtime;
                } else {
                    fzTime = "";
                }
                YiJiaHuNetWorkUtils.hospitalTimeUpdate(cyId, chuyaunTimeTV.getText().toString().trim(), fzId, fzTime, patientId, handler);
                break;

        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        iBack.putExtra("status", clickId);
        setResult(RESULT_OK, iBack);
        finish();
    }

    private class statusAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return hospitalStatus.size();
        }

        @Override
        public Object getItem(int position) {
            return hospitalStatus.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.adapter_patientstatus, null);
            TextView tv = (TextView) view.findViewById(R.id.tv_patientstatusselect);
            ImageView iv = (ImageView) view.findViewById(R.id.iv_patientstatusselect);

            HospitalStatusBean bean = hospitalStatus.get(position);
            tv.setText(bean.getName());
            if (bean.isSelect()) {
                iv.setVisibility(View.VISIBLE);
            } else {
                iv.setVisibility(View.INVISIBLE);
            }
            return view;
        }
    }
}
